import express, { Application } from "express";
import bodyParser from 'body-parser';
import { fileOperation } from "./utils";
import { ITodo } from "./typings";

const app: Application = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())

console.log('Welcome to EXPRESS')

app.all('*', (req, res, next) => { // 设置跨域
  res.header('Access-Control-Allow-Origin', '*'); // 所有请求的源都允许
  // 所有请求方式都允许
  res.header('Access-Control-Allow-methods', 'POST,GET,PUT,DELELTE,OPTIONS');
  next()
})


// CRUD
app.get('/todolist', function(req, res) {
  // const todoList: string = readFile('todo.json')
  const todoList = fileOperation('todo.json') as string;
  // console.log(todoList)
  res.send({
    msg: 'ok',
    statusCode: 200,
    data: todoList
  })
});

app.post('/add', function(req, res) {
  const todo: ITodo = JSON.parse(req.body.todo)

  fileOperation('todo.json', function (todoList: ITodo[]) {
    const isExist = todoList.find((t: ITodo) => t.content === todo.content)

    if (isExist) {
      res.send({
        msg: '数据已存在',
        statusCode: 100
      })
      return
    }
    todoList.push(todo)
    return todoList;
  })

  res.send({
    msg: 'ok',
    statusCode: 200
  });
});

app.post('/remove', function(req, res) { // 读取文件数据 修改后再写入
  const id: number = parseInt(req.body.id);
  // let todoList: ITodo[] = JSON.parse(readFile('todo.json') || '[]');
  // todoList = todoList.filter((item: ITodo) => item.id !== id);
  // writeFile('todo.json', todoList);

  fileOperation('todo.json', function (todoList: ITodo[]) {
    return todoList.filter((item: ITodo) => item.id !== id);
  })

  res.send({
    msg: 'ok',
    statusCode: 200
  });
});

app.post('/toggle', function(req, res) {
  const id: number = parseInt(req.body.id)

  fileOperation('todo.json', function (todoList: ITodo[]) {
    return todoList.map((item: ITodo) => {
      if (item.id === id) {
        item.completed = !item.completed;
      }
      return item
    });
  });

  res.send({
    msg: 'ok',
    statusCode: 200
  });
});


app.listen(8080, function() {
  console.log('Listening on port 8080');
});